<?php
// functions to send and receive xAP



function xAPSendHeartBeat(){
	global $config;

	$msg="xap-hbeat\n";
	$msg.="{\n";
	$msg.="v=12\n";
	$msg.="hop=1\n";
	$msg.="uid=".$config["xapuid"]."00\n";
	$msg.="class=xap-hbeat.alive\n";
	$msg.="source=".$config["xapsource"]."\n";
	$msg.="interval=".$config["xaphbeatinterval"]."\n";
	$msg.="port=".$config["xapport"]."\n";
	$msg.="}\n";
	
	xAPLog("xAP","Sending Hbeat","");
	xAPSendPacket($msg);
}

function xAPSendIntranet(){
	global $config;

	$msg="Server.Start\n";
	$msg.="{\n";
	$msg.="Name=".$config["appname"]."\n";
	$msg.="Desc=".$config["appdesc"]."\n";
	$msg.="Group=".$config["intranetgroup"]."\n";
	$msg.="PC=".$config["pcname"]."\n";
	$msg.="URL=".$config["url"].$config["modulefolder"]."/\n";
	$msg.="Icon=".$config["url"]."".$config["modulefolder"]."/images/icon.gif\n";
	$msg.="}\n";
	

	xAPSend("Web.Service",$msg);
}
function xAPSend($class,$body,$target=""){
	global $config;

	$msg="xap-header\n";
	$msg.="{\n";
	$msg.="v=12\n";
	$msg.="hop=1\n";
	$msg.="uid=".$config["xapuid"]."00\n";
	$msg.="class=".$class."\n";
	$msg.="source=".$config["xapsource"]."\n";
	if($target!=""){
		$msg.="target=".$target."\n";
	}
	$msg.="}\n";
	$msg.=$body;
	
	xAPLog("xAP","Sending ".$class,"");
	xAPSendPacket($msg);
}
function xAPSendSub($SubUID,$SubName,$class,$body,$target=""){
	global $config;
	$SubUID=str_pad($SubUID,2,"0",STR_PAD_LEFT);
	$msg="xap-header\n";
	$msg.="{\n";
	$msg.="v=12\n";
	$msg.="hop=1\n";
	$msg.="uid=".$config["xapuid"].$SubUID."\n";
	$msg.="class=".$class."\n";
	$msg.="source=".$config["xapsource"].":".$SubName."\n";
	if($target!=""){
		$msg.="target=".$target."\n";
	}
	$msg.="}\n";
	$msg.=$body;
	
	xAPLog("xAP","Sending Sub ".$class,$SubName);
	xAPSendPacket($msg);
}

function xAPSendPacket($msg){
	// actual packet sending
	global $config;
    $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
	socket_set_option($sock, SOL_SOCKET, SO_BROADCAST, 1); 
	$len = strlen($msg);
    socket_sendto($sock, $msg, $len, 0, $config["broadcast"], 3639);
    socket_close($sock);
	}
	
function xAPTimeToDBTime($xAPTime){
	if(strlen($xAPTime)==14){
		$tmp=substr($xAPTime,0,4)."-".substr($xAPTime,4,2)."-".substr($xAPTime,6,2)." ";
		$tmp.=substr($xAPTime,8,2).":".substr($xAPTime,10,2).":".substr($xAPTime,12,2);
	}
	else
	{
		$tmp=date("Y-m-d H:i:s");
	}

	return $tmp;

}

	
function xAPLog($category,$title,$description){
global $config;
	if($config["debug"]==1){
		$msg= date("H:m:s",time())." ".str_pad($config["appname"],15," ")." $category $title $description\r\n";
		$msg= time()." ".str_pad($config["appname"],15," ")." $category $title $description\r\n";
		echo $msg;
        //$STDOUT = fopen("php://output", "w");
        //fwrite($STDOUT, $msg);
        //fclose($STDOUT);
	}
}
?>